<!DOCTYPE html>
<html>

	<head>
		<meta charset="utf-8">
		<title>智慧大棚系统 - 计划管理</title>
		<script src="https://cdn.tailwindcss.com"></script>
		<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.7.2/css/all.min.css" rel="stylesheet">
		<script src="https://cdn.jsdelivr.net/npm/vue@3.3.11/dist/vue.global.prod.min.js"></script>
		<script src="https://cdn.jsdelivr.net/npm/axios@1.7.7/dist/axios.min.js"></script>
		<script src="https://cdn.jsdelivr.net/npm/dayjs@1.11.10/dayjs.min.js"></script>

		<!-- Tailwind配置 -->
		<script>
			tailwind.config = {
				theme: {
					extend: {
						colors: {
							primary: '#2E7D32', // 主色调：绿色，代表农业、生长
							secondary: '#1976D2', // 辅助色：蓝色，代表科技、数据
							accent: '#F59E0B', // 强调色：橙色，代表警告、提醒
							neutral: {
								100: '#F9FAFB',
								200: '#F3F4F6',
								300: '#E5E7EB',
								400: '#D1D5DB',
								500: '#9CA3AF',
								600: '#6B7280',
								700: '#4B5563',
								800: '#1F2937',
								900: '#111827'
							}
						},
						fontFamily: {
							inter: ['Inter', 'sans-serif'],
						},
						boxShadow: {
							'card': '0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06)',
							'card-hover': '0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -2px rgba(0, 0, 0, 0.05)',
						}
					},
				}
			}
		</script>

		<style type="text/tailwindcss">
			@layer utilities {
            .content-auto {
                content-visibility: auto;
            }
            .bg-grid {
                background-image: linear-gradient(#e5e7eb 1px, transparent 1px),
                                  linear-gradient(to right, #e5e7eb 1px, transparent 1px);
                background-size: 20px 20px;
            }
            .errmsg {
                @apply text-red-500 text-xs ml-2;
            }
            .management-title {
                @apply text-xl font-bold text-neutral-800 mb-4 border-b border-neutral-200 pb-2;
            }
            .management-title-dialog {
                @apply text-lg font-bold text-neutral-800 mb-4 border-b border-neutral-200 pb-2;
            }
            .search-container {
                @apply flex flex-wrap gap-2 mb-4;
            }
            .search-input {
                @apply px-3 py-2 border border-neutral-300 rounded-md focus:outline-none focus:ring-2 focus:ring-primary/50 focus:border-primary transition-all duration-200;
            }
            .search-button {
                @apply px-4 py-2 bg-primary text-white rounded-md hover:bg-primary/90 transition-colors duration-200;
            }
            .leftmargin {
                @apply ml-2;
            }
            .button-spacing {
                @apply mb-4;
            }
            .button {
                @apply px-4 py-2 bg-primary text-white rounded-md hover:bg-primary/90 transition-colors duration-200;
            }
            .editButton {
                @apply bg-blue-600 hover:bg-blue-700;
            }
            .deleteButton {
                @apply bg-red-600 hover:bg-red-700;
            }
            .detailButton {
                @apply bg-purple-600 hover:bg-purple-700;
            }
            .startButton {
                @apply bg-green-600 hover:bg-green-700;
            }
            .completeButton {
                @apply bg-teal-600 hover:bg-teal-700;
            }
            table {
                @apply w-full border-collapse;
            }
            th {
                @apply px-4 py-2 bg-neutral-100 text-left text-xs font-medium text-neutral-600 uppercase tracking-wider border border-neutral-200;
            }
            td {
                @apply px-4 py-2 border border-neutral-200;
            }
            tr:nth-child(even) {
                @apply bg-neutral-50;
            }
            tr:hover {
                @apply bg-neutral-100 transition-colors duration-150;
            }
            .pagination {
                @apply flex mt-4 space-x-2;
            }
            .pagination button {
                @apply px-3 py-1 border border-neutral-300 rounded hover:bg-neutral-100 transition-colors duration-150;
            }
            dialog {
                @apply fixed inset-0 m-auto w-1/2 max-w-md p-6 rounded-lg shadow-xl z-50 bg-white border-none;
            }
            dialog::backdrop {
                @apply bg-black/50 backdrop-blur-sm;
            }
            dialog form {
                @apply space-y-4;
            }
            dialog label {
                @apply block text-sm font-medium text-neutral-700 mb-1;
            }
            dialog input, dialog select, dialog textarea {
                @apply w-full px-3 py-2 border border-neutral-300 rounded-md focus:outline-none focus:ring-2 focus:ring-primary/50 focus:border-primary transition-all duration-200;
            }
            dialog textarea {
                @apply h-24 resize-none;
            }
            .sidebar {
                @apply w-64 bg-white border-r border-neutral-200 h-screen fixed left-0 top-0 pt-20 overflow-y-auto;
            }
            .sidebar ul {
                @apply space-y-1 px-2;
            }
            .sidebar li {
                @apply rounded-md;
            }
            .sidebar a {
                @apply block px-4 py-2 text-neutral-700 hover:bg-primary/10 hover:text-primary rounded-md transition-colors duration-200;
            }
            .sidebar a.active {
                @apply bg-primary/10 text-primary font-medium;
            }
            .header {
                @apply bg-white shadow-md fixed w-full z-50 h-20 flex items-center px-6;
            }
            .header h1 {
                @apply text-xl font-bold text-neutral-800 ml-2;
            }
            .content {
                @apply ml-64 pt-20 px-6 pb-10;
            }
            .highlight {
                @apply bg-yellow-100;
            }
            .status-planned {
                @apply bg-blue-100 text-blue-800 px-2 py-1 rounded-full text-xs;
            }
            .status-in-progress {
                @apply bg-yellow-100 text-yellow-800 px-2 py-1 rounded-full text-xs;
            }
            .status-completed {
                @apply bg-green-100 text-green-800 px-2 py-1 rounded-full text-xs;
            }
            .status-cancelled {
                @apply bg-red-100 text-red-800 px-2 py-1 rounded-full text-xs;
            }
            .readonly-input {
                @apply px-3 py-2 border border-neutral-300 rounded-md bg-neutral-100;
            }
        }
    </style>
	</head>

	<body>
		<div id="app">
			<div class="header">
				<!-- 加入 logo -->
				<div class="bg-primary text-white p-2 rounded-lg">
					<i class="fa-solid fa-farm text-xl"></i>
				</div>
				<h1>智慧大棚管理系统</h1>
			</div>

			<div class="container">
				<!-- 左侧导航栏 -->
				<div class="sidebar">
					<ul>
						<li><a href="/greenhouse/GreenHouseType/list.html" class="sidebar-item">大棚种类管理</a></li>
						<li><a href="/greenhouse/GreenHouseLocation/list.html" class="sidebar-item">大棚位置管理</a></li>
						<li><a href="/greenhouse/GreenHouse/list.html" class="sidebar-item">大棚管理</a></li>
						<li><a href="/greenhouse/Crops/list.html" class="sidebar-item">农产品管理</a></li>
						<li><a href="/greenhouse/PlanType/list.html" class="sidebar-item">计划分类管理</a></li>
						<li><a href="/greenhouse/Plan/list.html" class="sidebar-item">计划管理</a></li>
						<li><a href="/greenhouse/InputType/list.html" class="sidebar-item">投入类别管理</a></li>
						<li><a href="/greenhouse/Input/list.html" class="sidebar-item">投入管理</a></li>
						<li><a href="/greenhouse/Order/list.html" class="sidebar-item">订单管理</a></li>
						<li><a href="/greenhouse/Employee/list.html" class="sidebar-item">员工管理</a></li>
					</ul>
				</div>

				<!-- 内容区域 -->
				<div class="content">
					<h2 class="management-title">计划管理</h2>

					<div class="search-container">
						<input type="number" class="search-input" placeholder="输入年份" v-model="queryParam.year"
							@keyup.enter="query(1)">
						<input type="text" class="search-input" placeholder="输入大棚名称" v-model="queryParam.greenhouseName"
							@keyup.enter="query(1)">
						<input type="text" class="search-input" placeholder="输入计划名称" v-model="queryParam.planName"
							@keyup.enter="query(1)">
						<button class="search-button leftmargin" @click="query(1)">查询</button>
						<button class="button bg-neutral-600" @click="resetQuery">重置</button>
					</div>

					<div class="button-spacing">
						<button class="button" @click="openAddDialog">添加生产计划</button>
					</div>

					<table>
						<thead>
							<tr>
								<th>序号</th>
								<th>年份</th>
								<th>计划名称</th>
								<th>批次</th>
								<th>大棚名称</th>
								<th>农作物</th>
								<th>计划开始时间</th>
								<th>计划结束时间</th>
								<th>状态</th>
								<th>操作</th>
							</tr>
						</thead>
						<tbody>
							<tr v-for="(item, index) in filteredRecords" :key="item.id">
								<td>{{index + 1}}</td>
								<td>{{item.year}}</td>
								<td v-html="highlightText(item.planName, queryParam.planName)"></td>
								<td>{{item.batch}}</td>
								<td v-html="highlightText(item.greenhouseName, queryParam.greenhouseName)"></td>
								<td>{{item.crop}}</td>
								<td>{{formatDate(item.startDate)}}</td>
								<td>{{formatDate(item.endDate)}}</td>
								<td>
									<span :class="getStatusClass(item.status)">{{getStatusText(item.status)}}</span>
								</td>
								<td>
									<button class="button editButton" @click="openEditDialog(item.id)"
										v-if="item.status !== 'completed'">编辑</button>
									<button class="button deleteButton"
										@click="openDeleteConfirmDialog(item.id)">删除</button>
									<button class="button detailButton"
										@click="openPlanDetailDialog(item.id)">计划明细</button>
								</td>
							</tr>
							<tr v-if="filteredRecords.length === 0">
								<td colspan="10" class="text-center py-4 text-neutral-500">没有找到匹配的记录</td>
							</tr>
						</tbody>
					</table>

					<!-- 分页组件 -->
					<div class="pagination" v-if="page.pages > 1">
						<button @click="query(1)">首页</button>
						<button v-for="index in page.pages" @click="query(index)">{{index}}</button>
						<button @click="query(page.pages)">末页</button>
					</div>
				</div>
			</div>

			<!-- 添加数据的对话框 -->
			<dialog ref="addDialogRef">
				<h2 class="management-title-dialog">添加生产计划</h2>
				<form>
					<label>年份：</label>
					<input type="number" placeholder="输入年份" v-model="addParam.year">
					<span class="errmsg" v-show="errShow.year">请输入年份</span>

					<label>计划名称：</label>
					<input type="text" placeholder="输入计划名称" v-model="addParam.planName">
					<span class="errmsg" v-show="errShow.planName">请输入计划名称</span>

					<label>批次：</label>
					<input type="text" placeholder="输入批次" v-model="addParam.batch">
					<span class="errmsg" v-show="errShow.batch">请输入批次</span>

					<label>大棚名称：</label>
					<select v-model="addParam.greenhouseId">
						<option value="">选择大棚</option>
						<option v-for="greenhouse in greenhouses" :value="greenhouse.id">{{greenhouse.name}}</option>
					</select>
					<span class="errmsg" v-show="errShow.greenhouseId">请选择大棚</span>

					<label>农作物：</label>
					<select v-model="addParam.crop">
						<option value="">选择农作物</option>
						<option v-for="crop in crops" :value="crop">{{crop}}</option>
					</select>
					<span class="errmsg" v-show="errShow.crop">请选择农作物</span>

					<label>计划开始时间：</label>
					<input type="date" v-model="addParam.startDate">
					<span class="errmsg" v-show="errShow.startDate">请选择开始时间</span>

					<label>计划结束时间：</label>
					<input type="date" v-model="addParam.endDate">
					<span class="errmsg" v-show="errShow.endDate">请选择结束时间</span>

					<label>状态：</label>
					<select v-model="addParam.status">
						<option v-for="status in statusOptions" :value="status.value">{{status.label}}</option>
					</select>
					<span class="errmsg" v-show="errShow.status">请选择状态</span>

					<div class="flex justify-end space-x-2">
						<button class="button" type="button" @click="add">保存</button>
						<button class="button bg-neutral-600" type="button" @click="closeAddDialog">取消</button>
					</div>
					<span class="errmsg" v-show="errShow.addError">添加失败,请重新输入或者联系管理员</span>
				</form>
			</dialog>

			<!-- 编辑数据的对话框 -->
			<dialog ref="editDialogRef">
				<h2 class="management-title-dialog">编辑生产计划</h2>
				<form>
					<label>年份：</label>
					<p class="readonly-input">{{updateParam.year}}</p>

					<label>计划名称：</label>
					<p class="readonly-input">{{updateParam.planName}}</p>

					<label>批次：</label>
					<p class="readonly-input">{{updateParam.batch}}</p>

					<label>大棚名称：</label>
					<select v-model="updateParam.greenhouseId">
						<option v-for="greenhouse in greenhouses" :value="greenhouse.id">{{greenhouse.name}}</option>
					</select>
					<span class="errmsg" v-show="errShow.greenhouseId">请选择大棚</span>

					<label>农作物：</label>
					<select v-model="updateParam.crop">
						<option v-for="crop in crops" :value="crop">{{crop}}</option>
					</select>
					<span class="errmsg" v-show="errShow.crop">请选择农作物</span>

					<label>计划开始时间：</label>
					<p class="readonly-input">{{formatDate(updateParam.startDate)}}</p>

					<label>计划结束时间：</label>
					<p class="readonly-input">{{formatDate(updateParam.endDate)}}</p>

					<label>状态：</label>
					<select v-model="updateParam.status">
						<option v-for="status in statusOptions" :value="status.value">{{status.label}}</option>
					</select>
					<span class="errmsg" v-show="errShow.status">请选择状态</span>

					<div class="flex justify-end space-x-2">
						<button class="button" type="button" @click="update">保存</button>
						<button class="button bg-neutral-600" type="button" @click="closeEditDialog">取消</button>
					</div>
					<span class="errmsg" v-show="errShow.updateError">更新失败,请重新输入或者联系管理员</span>
				</form>
			</dialog>

			<!-- 删除确认对话框 -->
			<dialog ref="confirmDialogRef">
				<p>您确定删除该生产计划吗？</p>
				<div class="flex justify-end space-x-2">
					<button class="button" @click="confirmDelete">确定</button>
					<button class="button bg-neutral-600" @click="closeDeleteConfirmDialog">取消</button>
				</div>
			</dialog>

			<!-- 计划明细对话框 -->
			<dialog ref="planDetailDialogRef" class="w-3/4 max-w-4xl">
				<h2 class="management-title-dialog">计划明细</h2>
				<div class="mb-4 grid grid-cols-2 gap-4">
					<div>
						<p><strong>年份：</strong>{{currentPlan.year}}</p>
						<p><strong>计划名称：</strong>{{currentPlan.planName}}</p>
						<p><strong>批次：</strong>{{currentPlan.batch}}</p>
					</div>
					<div>
						<p><strong>大棚名称：</strong>{{currentPlan.greenhouseName}}</p>
						<p><strong>农作物：</strong>{{currentPlan.crop}}</p>
						<p><strong>计划时间：</strong>{{formatDate(currentPlan.startDate)}} 至
							{{formatDate(currentPlan.endDate)}}
						</p>
						<p><strong>状态：</strong><span
								:class="getStatusClass(currentPlan.status)">{{getStatusText(currentPlan.status)}}</span>
						</p>
					</div>
				</div>

				<div class="flex justify-between items-center mb-4">
					<h3 class="text-lg font-semibold">任务列表</h3>
					<button class="button" @click="openAddTaskDialog">添加任务</button>
				</div>

				<table>
					<thead>
						<tr>
							<th>序号</th>
							<th>计划分类</th>
							<th>计划详情</th>
							<th>温度要求</th>
							<th>湿度要求</th>
							<th>实际开始时间</th>
							<th>实际结束时间</th>
							<th>状态</th>
							<th>操作</th>
						</tr>
					</thead>
					<tbody>
						<tr v-for="(task, index) in currentPlan.tasks" :key="task.id">
							<td>{{index + 1}}</td>
							<td>{{task.category}}</td>
							<td>{{task.details || '-'}}</td>
							<td>{{task.temperature}}°C</td>
							<td>{{task.humidity}}%</td>
							<td>{{formatDate(task.plannedDate)}}</td>
							<td>{{task.actualDate ? formatDate(task.actualDate) : '-'}}</td>
							<td>
								<span :class="getStatusClass(task.status)">{{getStatusText(task.status)}}</span>
							</td>
							<td>
								<button class="button editButton" @click="openEditTaskDialog(task.id)"
									v-if="task.status !== 'completed' && task.status !== 'in-progress'">编辑</button>
								<button class="button deleteButton" @click="openDeleteTaskConfirmDialog(task.id)"
									v-if="task.status !== 'completed'">删除</button>
								<button class="button startButton" @click="startTask(task.id)"
									v-if="task.status === 'planned' && canStartTask(index)">开始</button>
								<button class="button completeButton" @click="completeTask(task.id)"
									v-if="task.status === 'in-progress'">完成</button>
							</td>
						</tr>
						<tr v-if="currentPlan.tasks && currentPlan.tasks.length === 0">
							<td colspan="9" class="text-center py-4 text-neutral-500">暂无任务</td>
						</tr>
					</tbody>
				</table>

				<div class="flex justify-end mt-4">
					<button class="button bg-neutral-600" @click="closePlanDetailDialog">关闭</button>
				</div>
			</dialog>

			<!-- 添加任务对话框 -->
			<dialog ref="addTaskDialogRef">
				<h2 class="management-title-dialog">添加任务</h2>
				<form>
					<label>计划分类：</label>
					<select v-model="addTaskParam.category">
						<option value="">选择计划分类</option>
						<option v-for="category in taskCategories" :value="category">{{category}}</option>
					</select>
					<span class="errmsg" v-show="errShow.taskCategory">请选择计划分类</span>

					<label>计划详情：</label>
					<textarea placeholder="输入计划详情" v-model="addTaskParam.details"></textarea>

					<label>温度要求：</label>
					<input type="number" placeholder="输入温度要求(°C)" v-model="addTaskParam.temperature">
					<span class="errmsg" v-show="errShow.taskTemperature">请输入温度要求</span>

					<label>湿度要求：</label>
					<input type="number" placeholder="输入湿度要求(%)" v-model="addTaskParam.humidity">
					<span class="errmsg" v-show="errShow.taskHumidity">请输入湿度要求</span>

					<label>计划完成时间：</label>
					<input type="date" v-model="addTaskParam.plannedDate">
					<span class="errmsg" v-show="errShow.taskPlannedDate">请选择计划完成时间</span>

					<label>状态：</label>
					<select v-model="addTaskParam.status">
						<option v-for="status in statusOptions" :value="status.value">{{status.label}}</option>
					</select>

					<div class="flex justify-end space-x-2">
						<button class="button" type="button" @click="addTask">保存</button>
						<button class="button bg-neutral-600" type="button" @click="closeAddTaskDialog">取消</button>
					</div>
				</form>
			</dialog>

			<!-- 编辑任务对话框 -->
			<dialog ref="editTaskDialogRef">
				<h2 class="management-title-dialog">编辑任务</h2>
				<form>
					<label>计划分类：</label>
					<p class="readonly-input">{{updateTaskParam.category}}</p>

					<label>计划详情：</label>
					<textarea v-model="updateTaskParam.details"></textarea>

					<label>温度要求：</label>
					<p class="readonly-input">{{updateTaskParam.temperature}}°C</p>

					<label>湿度要求：</label>
					<p class="readonly-input">{{updateTaskParam.humidity}}%</p>

					<label>计划完成时间：</label>
					<p class="readonly-input">{{formatDate(updateTaskParam.plannedDate)}}</p>

					<label>实际完成时间：</label>
					<input type="date" v-model="updateTaskParam.actualDate"
						v-if="updateTaskParam.status === 'completed'">
					<p class="readonly-input" v-else>-</p>

					<label>状态：</label>
					<select v-model="updateTaskParam.status">
						<option v-for="status in statusOptions" :value="status.value">{{status.label}}</option>
					</select>

					<div class="flex justify-end space-x-2">
						<button class="button" type="button" @click="updateTask">保存</button>
						<button class="button bg-neutral-600" type="button" @click="closeEditTaskDialog">取消</button>
					</div>
				</form>
			</dialog>

			<!-- 删除任务确认对话框 -->
			<dialog ref="confirmTaskDialogRef">
				<p>您确定删除该任务吗？</p>
				<div class="flex justify-end space-x-2">
					<button class="button" @click="confirmDeleteTask">确定</button>
					<button class="button bg-neutral-600" @click="closeDeleteTaskConfirmDialog">取消</button>
				</div>
			</dialog>
		</div>

		<script>
			const {
				createApp,
				ref,
				reactive,
				onMounted,
				computed,
				watch
			} = Vue;

			createApp({
				setup() {
					// 查询参数
					const queryParam = reactive({
						year: '',
						greenhouseName: '',
						planName: '',
						pageNum: 1,
						pageSize: 10
					});

					// 年份选项
					const years = ref([]);
					for (let i = 2020; i <= 2030; i++) {
						years.value.push(i);
					}

					// 大棚数据
					const greenhouses = ref([{
							id: 1,
							name: 'A区3排7号大棚',
							location: '温室园区A区',
							area: 300
						},
						{
							id: 2,
							name: 'B区2排5号大棚',
							location: '温室园区B区',
							area: 250
						},
						{
							id: 3,
							name: 'A区1排3号大棚',
							location: '温室园区A区',
							area: 200
						},
						{
							id: 4,
							name: 'C区5排2号大棚',
							location: '温室园区C区',
							area: 150
						},
						{
							id: 5,
							name: 'B区1排4号大棚',
							location: '温室园区B区',
							area: 280
						}
					]);

					// 农作物选项
					const crops = ref([
						'西红柿', '生菜', '黄瓜', '草莓', '辣椒',
						'茄子', '芹菜', '西兰花', '胡萝卜', '菠菜'
					]);

					// 任务分类选项
					const taskCategories = ref([
						'土地准备', '播种', '施肥', '浇水', '病虫害防治',
						'修剪', '收获', '包装', '运输', '销售'
					]);

					// 状态选项
					const statusOptions = ref([{
							value: 'planned',
							label: '计划中'
						},
						{
							value: 'in-progress',
							label: '进行中'
						},
						{
							value: 'completed',
							label: '已完成'
						},
						{
							value: 'cancelled',
							label: '已取消'
						}
					]);

					// 所有生产计划数据
					const allRecords = ref([{
							id: 1,
							year: 2023,
							planName: '春季西红柿种植计划',
							batch: '2023-001',
							greenhouseId: 1,
							greenhouseName: 'A区3排7号大棚',
							crop: '西红柿',
							startDate: '2023-03-01',
							endDate: '2023-06-30',
							status: 'completed',
							tasks: [{
									id: 1,
									category: '土地准备',
									temperature: 25,
									humidity: 60,
									details: '清理大棚内杂物，翻耕土地，施基肥',
									plannedDate: '2023-03-01',
									actualDate: '2023-03-02',
									status: 'completed'
								},
								{
									id: 2,
									category: '播种',
									temperature: 22,
									humidity: 65,
									details: '选用优质西红柿种子，进行播种',
									plannedDate: '2023-03-10',
									actualDate: '2023-03-10',
									status: 'completed'
								},
								{
									id: 3,
									category: '施肥',
									temperature: 24,
									humidity: 70,
									details: '根据生长情况，施加适量氮肥和磷肥',
									plannedDate: '2023-04-01',
									actualDate: '2023-04-02',
									status: 'completed'
								},
								{
									id: 4,
									category: '收获',
									temperature: 26,
									humidity: 55,
									details: '西红柿成熟后，进行采摘和包装',
									plannedDate: '2023-06-15',
									actualDate: '2023-06-14',
									status: 'completed'
								}
							]
						},
						{
							id: 2,
							year: 2023,
							planName: '夏季生菜种植计划',
							batch: '2023-002',
							greenhouseId: 2,
							greenhouseName: 'B区2排5号大棚',
							crop: '生菜',
							startDate: '2023-05-01',
							endDate: '2023-07-30',
							status: 'in-progress',
							tasks: [{
									id: 5,
									category: '土地准备',
									temperature: 20,
									humidity: 70,
									details: '清理大棚，翻耕土地，平整畦面',
									plannedDate: '2023-05-01',
									actualDate: '2023-05-01',
									status: 'completed'
								},
								{
									id: 6,
									category: '播种',
									temperature: 18,
									humidity: 75,
									details: '生菜种子播种，覆盖薄土，保持湿润',
									plannedDate: '2023-05-10',
									actualDate: '2023-05-11',
									status: 'completed'
								},
								{
									id: 7,
									category: '施肥',
									temperature: 22,
									humidity: 70,
									details: '生菜生长中期，追加氮肥',
									plannedDate: '2023-06-01',
									actualDate: null,
									status: 'in-progress'
								},
								{
									id: 8,
									category: '收获',
									temperature: 20,
									humidity: 65,
									details: '生菜成熟后，进行收割和包装',
									plannedDate: '2023-07-20',
									actualDate: null,
									status: 'planned'
								}
							]
						},
						{
							id: 3,
							year: 2023,
							planName: '秋季黄瓜种植计划',
							batch: '2023-003',
							greenhouseId: 3,
							greenhouseName: 'A区1排3号大棚',
							crop: '黄瓜',
							startDate: '2023-08-01',
							endDate: '2023-11-30',
							status: 'planned',
							tasks: [{
									id: 9,
									category: '土地准备',
									temperature: 28,
									humidity: 65,
									details: '清理前茬作物，消毒土壤，施足基肥',
									plannedDate: '2023-08-01',
									actualDate: null,
									status: 'planned'
								},
								{
									id: 10,
									category: '播种',
									temperature: 25,
									humidity: 70,
									details: '黄瓜种子播种，搭建支架',
									plannedDate: '2023-08-15',
									actualDate: null,
									status: 'planned'
								}
							]
						},
						{
							id: 4,
							year: 2023,
							planName: '冬季草莓种植计划',
							batch: '2023-004',
							greenhouseId: 4,
							greenhouseName: 'C区5排2号大棚',
							crop: '草莓',
							startDate: '2023-12-01',
							endDate: '2024-02-28',
							status: 'planned',
							tasks: []
						},
						{
							id: 5,
							year: 2023,
							planName: '春季辣椒种植计划',
							batch: '2023-005',
							greenhouseId: 5,
							greenhouseName: 'B区1排4号大棚',
							crop: '辣椒',
							startDate: '2023-03-15',
							endDate: '2023-07-15',
							status: 'cancelled',
							tasks: [{
									id: 11,
									category: '土地准备',
									temperature: 26,
									humidity: 60,
									details: '清理大棚，翻耕土地，施有机肥',
									plannedDate: '2023-03-15',
									actualDate: '2023-03-15',
									status: 'completed'
								},
								{
									id: 12,
									category: '播种',
									temperature: 24,
									humidity: 65,
									details: '辣椒种子播种，覆盖地膜',
									plannedDate: '2023-03-25',
									actualDate: null,
									status: 'cancelled'
								}
							]
						}
					]);

					// 分页结果
					const page = reactive({
						records: [],
						total: 0,
						pages: 1,
						pageNum: 1,
						pageSize: 10
					});

					// 高亮显示匹配文本
					const highlightText = (text, keyword) => {
						if (!keyword || !text) return text;
						const regex = new RegExp(keyword, 'gi');
						return text.replace(regex, match => `<span class="highlight">${match}</span>`);
					};

					// 格式化日期
					const formatDate = (dateString) => {
						if (!dateString) return '';
						return dayjs(dateString).format('YYYY-MM-DD');
					};

					// 获取状态文本
					const getStatusText = (status) => {
						const option = statusOptions.value.find(opt => opt.value === status);
						return option ? option.label : status;
					};

					// 获取状态对应的CSS类
					const getStatusClass = (status) => {
						switch (status) {
							case 'planned':
								return 'status-planned';
							case 'in-progress':
								return 'status-in-progress';
							case 'completed':
								return 'status-completed';
							case 'cancelled':
								return 'status-cancelled';
							default:
								return '';
						}
					};

					// 检查是否可以开始任务
					const canStartTask = (index) => {
						if (index === 0) return true;
						return currentPlan.tasks[index - 1].status === 'completed';
					};

					// 过滤记录（模糊查询）
					const filteredRecords = computed(() => {
						let records = [...allRecords.value];

						// 年份筛选
						if (queryParam.year) {
							records = records.filter(item => item.year == queryParam.year);
						}

						// 大棚名称模糊查询
						if (queryParam.greenhouseName) {
							const keyword = queryParam.greenhouseName.toLowerCase();
							records = records.filter(item =>
								item.greenhouseName.toLowerCase().includes(keyword)
							);
						}

						// 计划名称模糊查询
						if (queryParam.planName) {
							const keyword = queryParam.planName.toLowerCase();
							records = records.filter(item =>
								item.planName.toLowerCase().includes(keyword)
							);
						}

						// 分页处理
						const start = (queryParam.pageNum - 1) * queryParam.pageSize;
						const end = start + queryParam.pageSize;

						// 更新分页信息
						page.total = records.length;
						page.pages = Math.ceil(page.total / queryParam.pageSize);

						return records.slice(start, end);
					});

					// 添加参数
					const addParam = reactive({
						year: '',
						planName: '',
						batch: '',
						greenhouseId: '',
						crop: '',
						startDate: '',
						endDate: '',
						status: 'planned'
					});

					// 更新参数
					const updateParam = reactive({
						id: null,
						year: '',
						planName: '',
						batch: '',
						greenhouseId: '',
						greenhouseName: '',
						crop: '',
						startDate: '',
						endDate: '',
						status: ''
					});

					// 当前计划
					const currentPlan = reactive({
						id: null,
						year: '',
						planName: '',
						batch: '',
						greenhouseName: '',
						crop: '',
						startDate: '',
						endDate: '',
						status: '',
						tasks: []
					});

					// 添加任务参数
					const addTaskParam = reactive({
						category: '',
						details: '',
						temperature: '',
						humidity: '',
						plannedDate: '',
						status: 'planned'
					});

					// 更新任务参数
					const updateTaskParam = reactive({
						id: null,
						category: '',
						details: '',
						temperature: '',
						humidity: '',
						plannedDate: '',
						actualDate: '',
						status: ''
					});

					// 错误提示
					const errShow = reactive({
						year: false,
						planName: false,
						batch: false,
						greenhouseId: false,
						crop: false,
						startDate: false,
						endDate: false,
						status: false,
						addError: false,
						updateError: false,
						taskCategory: false,
						taskTemperature: false,
						taskHumidity: false,
						taskPlannedDate: false
					});

					// 对话框引用
					const addDialogRef = ref(null);
					const editDialogRef = ref(null);
					const confirmDialogRef = ref(null);
					const planDetailDialogRef = ref(null);
					const addTaskDialogRef = ref(null);
					const editTaskDialogRef = ref(null);
					const confirmTaskDialogRef = ref(null);

					// 当前操作的ID
					const currentId = ref(null);
					const currentTaskId = ref(null);

					// 重置查询条件
					const resetQuery = () => {
						queryParam.year = '';
						queryParam.greenhouseName = '';
						queryParam.planName = '';
						queryParam.pageNum = 1;
						query(1);
					};

					// 查询数据
					const query = (pageNum) => {
						queryParam.pageNum = pageNum;
						// 这里不需要实际API调用，因为使用了computed属性自动过滤
					};

					// 生命周期钩子 - 页面加载完成后执行
					onMounted(() => {
						// 初始化加载数据
						query(1);
					});

					// 打开添加对话框
					const openAddDialog = () => {
						// 重置添加参数
						Object.assign(addParam, {
							year: '',
							planName: '',
							batch: '',
							greenhouseId: '',
							crop: '',
							startDate: '',
							endDate: '',
							status: 'planned'
						});

						// 重置错误提示
						resetErrorShow();

						// 显示对话框
						addDialogRef.value.showModal();
					};

					// 关闭添加对话框
					const closeAddDialog = () => {
						addDialogRef.value.close();
					};

					// 添加生产计划
					const add = () => {
						// 表单验证
						if (!validateAddForm()) {
							return;
						}

						// 模拟API调用
						setTimeout(() => {
							// 查找大棚名称
							const greenhouse = greenhouses.value.find(g => g.id === parseInt(addParam
								.greenhouseId));

							// 生成新ID
							const newId = Math.max(...allRecords.value.map(item => item.id)) + 1;

							// 添加新记录
							allRecords.value.push({
								id: newId,
								year: addParam.year,
								planName: addParam.planName,
								batch: addParam.batch,
								greenhouseId: addParam.greenhouseId,
								greenhouseName: greenhouse ? greenhouse.name : '',
								crop: addParam.crop,
								startDate: addParam.startDate,
								endDate: addParam.endDate,
								status: addParam.status,
								tasks: []
							});

							// 重新查询
							query(1);
							closeAddDialog();
							alert('添加成功');
						}, 300);
					};

					// 打开编辑对话框
					const openEditDialog = (id) => {
						// 找到要编辑的数据
						const item = allRecords.value.find(item => item.id === id);

						if (item) {
							// 复制数据到更新参数
							Object.assign(updateParam, {
								id: item.id,
								year: item.year,
								planName: item.planName,
								batch: item.batch,
								greenhouseId: item.greenhouseId,
								greenhouseName: item.greenhouseName,
								crop: item.crop,
								startDate: item.startDate,
								endDate: item.endDate,
								status: item.status
							});

							// 重置错误提示
							resetErrorShow();

							// 显示对话框
							editDialogRef.value.showModal();
						}
					};

					// 关闭编辑对话框
					const closeEditDialog = () => {
						editDialogRef.value.close();
					};

					// 更新生产计划
					const update = () => {
						// 表单验证
						if (!validateUpdateForm()) {
							return;
						}

						// 模拟API调用
						setTimeout(() => {
							// 找到要更新的数据
							const index = allRecords.value.findIndex(item => item.id === updateParam.id);

							if (index !== -1) {
								// 更新大棚名称
								const greenhouse = greenhouses.value.find(g => g.id === parseInt(updateParam
									.greenhouseId));
								const updatedItem = {
									...allRecords.value[index],
									greenhouseId: updateParam.greenhouseId,
									greenhouseName: greenhouse ? greenhouse.name : '',
									crop: updateParam.crop,
									status: updateParam.status
								};

								// 更新数据
								allRecords.value.splice(index, 1, updatedItem);

								// 如果当前查看的是该计划，也更新
								if (currentPlan.id === updateParam.id) {
									Object.assign(currentPlan, updatedItem);
								}

								// 重新查询
								query(queryParam.pageNum);
								closeEditDialog();
								alert('更新成功');
							}
						}, 300);
					};

					// 打开删除确认对话框
					const openDeleteConfirmDialog = (id) => {
						currentId.value = id;
						confirmDialogRef.value.showModal();
					};

					// 关闭删除确认对话框
					const closeDeleteConfirmDialog = () => {
						confirmDialogRef.value.close();
					};

					// 确认删除
					const confirmDelete = () => {
						// 模拟API调用
						setTimeout(() => {
							// 找到要删除的数据
							const index = allRecords.value.findIndex(item => item.id === currentId.value);

							if (index !== -1) {
								// 删除数据
								allRecords.value.splice(index, 1);

								// 重新查询
								query(1);
								closeDeleteConfirmDialog();
								alert('删除成功');
							}
						}, 300);
					};

					// 打开计划详情对话框
					const openPlanDetailDialog = (id) => {
						// 找到要查看的数据
						const item = allRecords.value.find(item => item.id === id);

						if (item) {
							// 复制数据到当前计划
							Object.assign(currentPlan, item);

							// 显示对话框
							planDetailDialogRef.value.showModal();
						}
					};

					// 关闭计划详情对话框
					const closePlanDetailDialog = () => {
						planDetailDialogRef.value.close();
					};

					// 打开添加任务对话框
					const openAddTaskDialog = () => {
						// 重置添加任务参数
						Object.assign(addTaskParam, {
							category: '',
							details: '',
							temperature: '',
							humidity: '',
							plannedDate: '',
							status: 'planned'
						});

						// 重置错误提示
						resetErrorShow();

						// 显示对话框
						addTaskDialogRef.value.showModal();
					};

					// 关闭添加任务对话框
					const closeAddTaskDialog = () => {
						addTaskDialogRef.value.close();
					};

					// 添加任务
					const addTask = () => {
						// 表单验证
						if (!validateAddTaskForm()) {
							return;
						}

						// 模拟API调用
						setTimeout(() => {
							// 生成新任务ID
							let newTaskId = 1;
							if (currentPlan.tasks && currentPlan.tasks.length > 0) {
								newTaskId = Math.max(...currentPlan.tasks.map(task => task.id)) + 1;
							}

							// 添加新任务
							currentPlan.tasks.push({
								id: newTaskId,
								category: addTaskParam.category,
								details: addTaskParam.details,
								temperature: addTaskParam.temperature,
								humidity: addTaskParam.humidity,
								plannedDate: addTaskParam.plannedDate,
								actualDate: null,
								status: addTaskParam.status
							});

							// 更新主数据
							const index = allRecords.value.findIndex(item => item.id === currentPlan.id);
							if (index !== -1) {
								allRecords.value[index].tasks = [...currentPlan.tasks];
							}

							// 关闭对话框
							closeAddTaskDialog();
							alert('添加任务成功');
						}, 300);
					};

					// 打开编辑任务对话框
					const openEditTaskDialog = (id) => {
						// 找到要编辑的任务
						const task = currentPlan.tasks.find(task => task.id === id);

						if (task) {
							// 复制数据到更新任务参数
							Object.assign(updateTaskParam, task);

							// 重置错误提示
							resetErrorShow();

							// 显示对话框
							editTaskDialogRef.value.showModal();
						}
					};

					// 关闭编辑任务对话框
					const closeEditTaskDialog = () => {
						editTaskDialogRef.value.close();
					};

					// 更新任务
					const updateTask = () => {
						// 模拟API调用
						setTimeout(() => {
							// 找到要更新的任务
							const index = currentPlan.tasks.findIndex(task => task.id === updateTaskParam
								.id);

							if (index !== -1) {
								// 更新任务
								currentPlan.tasks.splice(index, 1, {
									...updateTaskParam
								});

								// 更新主数据
								const planIndex = allRecords.value.findIndex(item => item.id === currentPlan
									.id);
								if (planIndex !== -1) {
									allRecords.value[planIndex].tasks = [...currentPlan.tasks];
								}

								// 关闭对话框
								closeEditTaskDialog();
								alert('更新任务成功');
							}
						}, 300);
					};

					// 打开删除任务确认对话框
					const openDeleteTaskConfirmDialog = (id) => {
						currentTaskId.value = id;
						confirmTaskDialogRef.value.showModal();
					};

					// 关闭删除任务确认对话框
					const closeDeleteTaskConfirmDialog = () => {
						confirmTaskDialogRef.value.close();
					};

					// 确认删除任务
					const confirmDeleteTask = () => {
						// 模拟API调用
						setTimeout(() => {
							// 找到要删除的任务
							const index = currentPlan.tasks.findIndex(task => task.id === currentTaskId
								.value);

							if (index !== -1) {
								// 删除任务
								currentPlan.tasks.splice(index, 1);

								// 更新主数据
								const planIndex = allRecords.value.findIndex(item => item.id === currentPlan
									.id);
								if (planIndex !== -1) {
									allRecords.value[planIndex].tasks = [...currentPlan.tasks];
								}

								// 关闭对话框
								closeDeleteTaskConfirmDialog();
								alert('删除任务成功');
							}
						}, 300);
					};

					// 开始任务
					const startTask = (id) => {
						// 找到要开始的任务
						const task = currentPlan.tasks.find(task => task.id === id);

						if (task) {
							// 更新任务状态
							task.status = 'in-progress';

							// 更新主数据
							const planIndex = allRecords.value.findIndex(item => item.id === currentPlan.id);
							if (planIndex !== -1) {
								allRecords.value[planIndex].tasks = [...currentPlan.tasks];
							}

							alert('任务已开始');
						}
					};

					// 完成任务
					const completeTask = (id) => {
						// 找到要完成的任务
						const task = currentPlan.tasks.find(task => task.id === id);

						if (task) {
							// 更新任务状态和实际完成时间
							task.status = 'completed';
							task.actualDate = dayjs().format('YYYY-MM-DD');

							// 检查是否所有任务都已完成，如果是则更新计划状态
							const allCompleted = currentPlan.tasks.every(task => task.status === 'completed');
							if (allCompleted) {
								currentPlan.status = 'completed';

								// 更新主数据中的计划状态
								const planIndex = allRecords.value.findIndex(item => item.id === currentPlan.id);
								if (planIndex !== -1) {
									allRecords.value[planIndex].status = 'completed';
								}
							}

							alert('任务已完成');
						}
					};

					// 表单验证 - 添加计划
					const validateAddForm = () => {
						let isValid = true;

						resetErrorShow();

						if (!addParam.year) {
							errShow.year = true;
							isValid = false;
						}

						if (!addParam.planName) {
							errShow.planName = true;
							isValid = false;
						}

						if (!addParam.batch) {
							errShow.batch = true;
							isValid = false;
						}

						if (!addParam.greenhouseId) {
							errShow.greenhouseId = true;
							isValid = false;
						}

						if (!addParam.crop) {
							errShow.crop = true;
							isValid = false;
						}

						if (!addParam.startDate) {
							errShow.startDate = true;
							isValid = false;
						}

						if (!addParam.endDate) {
							errShow.endDate = true;
							isValid = false;
						}

						if (addParam.startDate && addParam.endDate && addParam.startDate > addParam.endDate) {
							errShow.startDate = true;
							errShow.endDate = true;
							alert('开始日期不能晚于结束日期');
							isValid = false;
						}

						if (!addParam.status) {
							errShow.status = true;
							isValid = false;
						}

						return isValid;
					};

					// 表单验证 - 更新计划
					const validateUpdateForm = () => {
						let isValid = true;

						resetErrorShow();

						if (!updateParam.greenhouseId) {
							errShow.greenhouseId = true;
							isValid = false;
						}

						if (!updateParam.crop) {
							errShow.crop = true;
							isValid = false;
						}

						if (!updateParam.status) {
							errShow.status = true;
							isValid = false;
						}

						return isValid;
					};

					// 表单验证 - 添加任务
					const validateAddTaskForm = () => {
						let isValid = true;

						resetErrorShow();

						if (!addTaskParam.category) {
							errShow.taskCategory = true;
							isValid = false;
						}

						if (!addTaskParam.temperature) {
							errShow.taskTemperature = true;
							isValid = false;
						}

						if (!addTaskParam.humidity) {
							errShow.taskHumidity = true;
							isValid = false;
						}

						if (!addTaskParam.plannedDate) {
							errShow.taskPlannedDate = true;
							isValid = false;
						}

						return isValid;
					};

					// 重置错误提示
					const resetErrorShow = () => {
						Object.keys(errShow).forEach(key => {
							errShow[key] = false;
						});
					};

					return {
						queryParam,
						years,
						greenhouses,
						crops,
						taskCategories,
						statusOptions,
						filteredRecords,
						page,
						highlightText,
						formatDate,
						getStatusText,
						getStatusClass,
						canStartTask,
						addParam,
						updateParam,
						currentPlan,
						addTaskParam,
						updateTaskParam,
						errShow,
						addDialogRef,
						editDialogRef,
						confirmDialogRef,
						planDetailDialogRef,
						addTaskDialogRef,
						editTaskDialogRef,
						confirmTaskDialogRef,
						resetQuery,
						query,
						openAddDialog,
						closeAddDialog,
						add,
						openEditDialog,
						closeEditDialog,
						update,
						openDeleteConfirmDialog,
						closeDeleteConfirmDialog,
						confirmDelete,
						openPlanDetailDialog,
						closePlanDetailDialog,
						openAddTaskDialog,
						closeAddTaskDialog,
						addTask,
						openEditTaskDialog,
						closeEditTaskDialog,
						updateTask,
						openDeleteTaskConfirmDialog,
						closeDeleteTaskConfirmDialog,
						confirmDeleteTask,
						startTask,
						completeTask
					};
				}
			}).mount('#app');
		</script>
	</body>

</html>